<template>
	<view class="address-page">
		<!-- 地址列表 -->
		<scroll-view 
			scroll-y 
			class="address-list" 
			:style="{ height: scrollHeight + 'px' }"
			@scrolltolower="onLoadMore"
			refresher-enabled
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
		>
			<view v-if="addressList.length > 0">
				<view class="address-item" v-for="item in addressList" :key="item.id" @tap="handleAddressClick(item)">
					<view class="address-info">
						<view class="user-info">
							<text class="name">{{item.receiverName}}</text>
							<text class="phone">{{item.receiverPhone}}</text>
							<text class="tag default" v-if="item.isDefault">默认</text>
						</view>
						<view class="address-detail">
							<text>{{item.detailAddress}}{{item.addressDetail}}</text>
						</view>
					</view>
					<view class="action-btns">
						<view class="edit-btn" @tap.stop="editAddress(item)">
							<uv-icon name="edit-pen" size="40" color="#666"></uv-icon>
						</view>
						<view class="delete-btn" @tap.stop="deleteAddress(item)">
							<uv-icon name="trash" size="40" color="#ff5555"></uv-icon>
						</view>
					</view>
				</view>
				
				<!-- 加载更多提示 -->
				<view class="load-more" v-if="addressList.length > 0">
					<view class="load-more-content">
						<uv-loading-icon v-if="hasMore" size="24" mode="circle"></uv-loading-icon>
						<text class="text">{{ hasMore ? '正在加载...' : '- 没有更多了 -' }}</text>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty-state" v-else>
				<uv-empty
					mode="address"
					icon="map"
					text="暂无收货地址"
					:margin-top="60"
					:icon-size="120"
				>
					<template #bottom>
						<button class="empty-btn" @tap="addAddress">
							<uv-icon name="plus" size="24" color="#fff" margin-right="4"></uv-icon>
							新增地址
						</button>
					</template>
				</uv-empty>
			</view>
		</scroll-view>

		<!-- 底部按钮 -->
		<view class="action-bar" :style="{ bottom: safeAreaInsets.bottom + 'px' }">
			<button class="add-btn" @tap="addAddress">
				<uv-icon name="plus" size="32" color="#fff"></uv-icon>
				新增收货地址
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				addressList: [],
				pageNum: 1,
				pageSize: 10,
				total: 0,
				hasMore: true,
				isRefreshing: false,
				isLoading: false,
				scrollHeight: 0,
				safeAreaInsets: uni.getSystemInfoSync().safeAreaInsets || { bottom: 0 },
				from: ''
			}
		},
		
		onLoad(options) {
			// 获取来源页面
			this.from = options.from || ''
			
			// 计算滚动区域高度
			const systemInfo = uni.getSystemInfoSync()
			this.scrollHeight = systemInfo.windowHeight - 104 - (systemInfo.safeAreaInsets?.bottom || 0)
			
			// 加载地址列表
			this.loadAddressList()
		},
		
		methods: {
			// 加载地址列表
			async loadAddressList(type = 'init') {
				if (this.isLoading) return
				
				try {
					this.isLoading = true
					
					const data = await this.$http.get('/address/list', {
						params: {
							pageNum: this.pageNum,
							pageSize: this.pageSize
						}
					})
					
					if (data) {
						// 处理列表数据
						if (type === 'refresh' || type === 'init') {
							this.addressList = data.items
						} else {
							this.addressList = [...this.addressList, ...data.items]
						}
						
						// 更新分页信息
						this.total = data.count
						this.hasMore = this.addressList.length < data.count
						
						// 重置刷新状态
						if (type === 'refresh') {
							this.isRefreshing = false
						}
					}
				} catch (e) {
					console.error('获取地址列表失败:', e)
					uni.showToast({
						title: '获取地址列表失败',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},
			
			// 下拉刷新
			async onRefresh() {
				this.pageNum = 1
				this.isRefreshing = true
				await this.loadAddressList('refresh')
			},
			
			// 加载更多
			async onLoadMore() {
				if (!this.hasMore || this.isLoading) return
				
				this.pageNum++
				await this.loadAddressList('more')
			},
			
			// 选择地址
			selectAddress(address) {
				if (this.from) {
					// 如果是从其他页面跳转来的，选择地址后返回
					const pages = getCurrentPages()
					const prevPage = pages[pages.length - 2]
					
					// 设置上一页的地址数据
					if (prevPage) {
						prevPage.$vm.address = address
					}
					
					uni.navigateBack()
				}
			},
			
			// 新增地址
			addAddress() {
				uni.navigateTo({
					url: '/subpkg/add_address/add_address'
				})
			},
			
			// 编辑地址
			editAddress(address) {
				uni.navigateTo({
					url: `/subpkg/add_address/add_address?id=${address.id}`
				})
			},
			
			// 删除地址
			deleteAddress(address) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该地址吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$http.delete(`/address/delete/${address.id}`)
								this.pageNum = 1
								this.loadAddressList()
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
							} catch (e) {
								console.error('删除地址失败:', e)
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			// 新增处理地址点击的方法
			handleAddressClick(address) {
				if (this.from) {
					// 如果有来源页面，则是选择地址
					this.selectAddress(address)
				} else {
					// 否则是编辑地址
					this.editAddress(address)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'address.scss';
</style>
